<template>
  <div>
    <tabs :tabs="tabs" />
    <div class="edit-form">
      <el-form label-width="100px" :model="form" size="mini">
        <div class="edit-title">基本信息</div>
        <el-form-item label="所属题库">{{ form.bank_title }}</el-form-item>
        <el-form-item label="题目类型">
          <el-radio-group v-model="form.type" @change="topicChange">
            <el-radio v-for="(item, index) in questionType" :key="index" :label="item.value" disabled>{{ item.title }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干">
          <div class="editor-simple"><in-editor v-model="form.title" placeholder="请输入题干内容" /></div>
        </el-form-item>
        <!-- 单选/多选/判断/不定项 有选项-->
        <el-form-item v-if="$util.inArray(form.type, [1, 2, 3, 4])" label="选项">
          <el-row v-for="(item, i) in optionsData" :key="i" class="edit-options" type="flex" align="middle">
            <div class="title">选项{{ item.key }}</div>
            <div class="content"><in-editor v-model="item.value" placeholder="请输入选项内容" /></div>
            <el-radio v-if="$util.inArray(form.type, [1, 2])" v-model="form.answer" :label="item.key">正确</el-radio>
            <el-checkbox-group v-else v-model="form.answers"><el-checkbox :label="item.key">正确</el-checkbox></el-checkbox-group>
            <div class="delete el-icon-delete" @click="removeOptions(item, i)" />
          </el-row>
          <el-row v-if="form.type != 2" type="flex" justify="center">
            <el-button type="primary" plain icon="el-icon-plus" :disabled="optionsDisabled" @click="addOptions">新增选项({{ optionsData.length }}/26)</el-button>
          </el-row>
        </el-form-item>
        <!-- 填空题答案面板 -->
        <div v-else-if="form.type == 5">
          <el-form-item label="答案">
            <div v-for="(item, i) in optionsData" :key="i" class="answer-wrap">
              <el-row class="" type="flex" justify="space-between">
                <div class="title">第{{ i + 1 }}空</div>
                <div>
                  <div class="el-icon-bottom" @click="moveDown(i)" />
                  <div class="el-icon-top" @click="moveUp(i)" />
                  <div class="delete el-icon-delete" @click="removeOptions(item, i)" />
                </div>
              </el-row>
              <div v-for="(ans, vi) in item.value" :key="vi" class="add-answer">
                <el-row class="item" type="flex" align="middle">
                  <div v-if="vi > 0" class="or">或</div>
                  <el-input v-model="ans.val" />
                  <div class="delete el-icon-delete" @click="removeCompletionAnswer(i, vi)" />
                </el-row>
              </div>
              <el-link class="add-input-btn" icon="el-icon-plus" type="primary" :underline="false" @click="addCompletionAnswer(i)">添加答案</el-link>
            </div>
            <el-row type="flex" justify="center">
              <el-button type="primary" plain icon="el-icon-plus" :disabled="optionsDisabled" @click="addOptions">新增选项({{ optionsData.length }}/26)</el-button>
            </el-row>
          </el-form-item>
          <el-form-item label="答案位置不限"><el-switch v-model="completionPosition" :active-value="1" :inactive-value="0" /></el-form-item>
        </div>
        <!-- 简答题有参考答案 -->
        <el-form-item v-else-if="form.type == 8" label="参考答案">
          <el-row class="edit-options" type="flex" align="middle">
            <div class="content"><in-editor v-model="form.answer" /></div>
          </el-row>
        </el-form-item>
        <div class="edit-title">其他信息</div>
        <el-form-item label="知识点">
          <el-row type="flex"><choose-point :value.sync="form.point" :bank-id="form.bank_id" :cates="form.bank_cates" /></el-row>
        </el-form-item>
        <el-form-item label="难易度">
          <el-radio-group v-model="form.difficulty">
            <el-radio v-for="(item, index) in difficulty" :key="index" :label="item.value">{{ item.title }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.type != 6" label="题目解析">
          <div class="editor-simple"><in-editor v-model="form.analyze" placeholder="请输入解析内容" /></div>
        </el-form-item>
        <!-- 材料题添加子题 -->
        <materials v-if="form.type == 6" :difficulty="difficulty" :value.sync="subTopic" disabled-change-type />
        <!-- 完形填空添加子题 -->
        <cloze-test v-else-if="form.type == 7" :difficulty="difficulty" :value.sync="subTopic" />
        <el-row type="flex" justify="center"><el-button type="primary" size="mini" @click="submit">保存</el-button></el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import materials from './components/materials.vue';
import InEditor from '@/components/ue-editor-wrap';
import clozeTest from './components/cloze_test.vue';
import choosePoint from '@/pages/exam/question/point/choose';
import Tabs from './tabs';
export default {
  components: {
    materials,
    clozeTest,
    InEditor,
    choosePoint,
    Tabs
  },
  data() {
    return {
      tabs: [
        {
          title: '编辑题目',
          uri: '/exam/question/topic/' + this.$route.params.id + '/edit',
          meta: {
            permission: 'exam.question.topic.edit'
          }
        }
      ],
      form: {
        bank_title: '', // 题库
        title: '', // 题干
        type: 1, // 题型
        difficulty: 1, // 难易度
        answer: '', // 答案
        answers: [], // 多项答案
        point: [], // 知识点
        analyze: '' // 解析
      },
      // 值是否为数组
      isArrayValue: false,
      completionPosition: 0,
      // 题目类型 1:单选 2:判断 3:多选 4:不定项 5:填空 6:材料 7:完形填空 8:简答题
      questionType: [],
      // 题选项KEY
      optionsBasis: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
      // 答案
      optionsData: [
        {
          key: 'A',
          value: ''
        },
        {
          key: 'B',
          value: ''
        },
        {
          key: 'C',
          value: ''
        },
        {
          key: 'D',
          value: ''
        }
      ],
      optionsDisabled: false,
      // 难易度
      difficulty: [],
      saveMethod: 'post',
      savePostUrl: '',
      subTopic: []
    };
  },
  created() {
    this.$http.get(
      '/exam/admin/question/topic/' + this.$route.params.id + '/edit',
      {},
      response => {
        const {
          data: { difficulty, questionType, datas, answer, answers, options, point, saveMethod, savePostUrl }
        } = response;

        this.saveMethod = saveMethod;
        this.savePostUrl = savePostUrl;
        const form = {
          bank_title: datas.bank_title, // 题库名称
          bank_id: datas.question_bank_id, // 题库ID
          bank_cates: datas.bank_cates, // 题库category
          title: datas.title, // 题干
          type: datas.question_type, // 题型
          difficulty: datas.difficulty, // 难易度
          answer: answer, // 答案
          answers: answers, // 多项答案
          point: point, // 知识点
          analyze: datas.analyze // 解析
        };
        this.form = form;
        // 填空题  答案为数组
        if (form.type == 5) {
          this.isArrayValue = true;
        }
        // 材料题和完形填空,有子题
        if (form.type == 6 || form.type == 7) {
          this.subTopic = options;
          this.form.type = form.type;
        } else {
          this.optionsData = options;
        }
        this.difficulty = difficulty;
        this.questionType = questionType;
        this.completionPosition = datas.completion_position;
      },
      errpr => {}
    );
  },
  methods: {
    // 添加选项
    addOptions() {
      // 最多添加26个选项
      const length = this.optionsData.length;
      if (length > this.optionsBasis.length) {
        this.optionsDisabled = true;
        return;
      }
      this.optionsData.push({
        key: this.optionsBasis[this.optionsData.length],
        value: this.isArrayValue ? [{ val: '' }] : ''
      });

      if (length + 1 == this.optionsBasis.length) {
        this.optionsDisabled = true;
      }
    },

    // 删除选项
    removeOptions(item, i) {
      if (this.optionsData.length >= 2) {
        this.$box
          .confirm('确认删除该选项吗')
          .then(() => {
            var indexs = this.optionsData.indexOf(item);
            if (indexs !== -1) {
              this.optionsData.splice(i, 1);
            }
            for (let i = 0; i < this.optionsData.length; i++) {
              this.optionsData[i].key = this.optionsBasis[i];
            }

            if (this.optionsData.length < this.optionsBasis.length) {
              this.optionsDisabled = false;
            }
          })
          .catch(() => {});
      }
    },

    // 添加完形填空答案
    addCompletionAnswer(i) {
      const ansers = this.optionsData[i].value;
      ansers.push({ val: '' });
      this.optionsData[i].value = ansers;
    },

    // 移除完形填空答案
    removeCompletionAnswer(i, vi) {
      this.$box
        .confirm('确认移除该答案吗')
        .then(() => {
          const ansers = this.optionsData[i].value;
          ansers.splice(vi, 1);

          this.optionsData[i].value = ansers;
        })
        .catch(() => {});
    },

    // 类型切换
    topicChange(val) {
      // 判断题默认2个选项,其他默认4个
      this.optionsData = [];
      this.isArrayValue = false;
      this.$set(this.form, 'answer', '');
      this.$set(this.form, 'answers', []);
      this.subTopic = [];
      this.$nextTick(() => {
        if (val == 2) {
          // 判断题,固定两个答案: 正确和错误
          this.setOptionsData(2, val);
        } else if (this.$util.inArray(val, [1, 3, 4])) {
          // 选择,至少有2个答案,通常为4个答案
          this.setOptionsData(4);
        } else if (val == 5) {
          // 填空题,至少有一个答案
          this.isArrayValue = true;
          this.setOptionsData(1);
        }
      });
    },
    // 设置选项数量
    setOptionsData(num, type) {
      if (type == 2) {
        this.optionsData = [
          {
            key: this.optionsBasis[0],
            value: '正确'
          },
          {
            key: this.optionsBasis[1],
            value: '错误'
          }
        ];
      } else {
        for (let i = 0; i < num; i++) {
          this.optionsData.push({
            key: this.optionsBasis[i],
            value: this.isArrayValue ? [{ val: '' }] : ''
          });
        }
      }
    },
    submit() {
      const data = {
        ...this.form,
        completion_position: this.completionPosition,
        options: this.optionsData
      };
      if (data.type == 3 && data.answers.length < 2) {
        this.$message.warning('多选题至少选择2个正确答案');
        return false;
      } else if ((data.type == 1 || data.type == 2) && this.form.answer == '') {
        this.$message.warning('请选择正确答案');
        return false;
      }
      // 是否为材料题或完型填空题
      if (data.type == 6 || data.type == 7) {
        data.sub_topic = [];
        this.subTopic.forEach(item => {
          data.sub_topic.push({
            ...item.form,
            options: item.optionsData
          });
        });
      }

      this.$http.send(
        this.saveMethod,
        this.savePostUrl,
        data,
        response => {
          this.$message.success('修改成功');
        },
        error => {
          this.$message.error(error.msg);
        }
      );
    },
    // 上移
    moveUp(index) {
      var that = this;
      if (index > 0) {
        const upDate = that.optionsData[index - 1];
        that.optionsData.splice(index - 1, 1);
        that.optionsData.splice(index, 0, upDate);
      }
    },
    // 下移
    moveDown(index) {
      var that = this;
      if (index + 1 === that.optionsData.length) {
        console.log('已经是最后一条');
      } else {
        const downDate = that.optionsData[index + 1];
        that.optionsData.splice(index + 1, 1);
        that.optionsData.splice(index, 0, downDate);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.edit-form {
  padding: 0 36px 17px 20px;
  .edit-title {
    height: 36px;
    font-size: 15px;
    line-height: 36px;
    font-weight: 500;
    color: #303133;
    padding-left: 10px;
    position: relative;
    background: rgba(241, 248, 255, 0.8);
    margin-bottom: 24px;
    &::after {
      content: '';
      width: 2px;
      height: 14px;
      background: #5191ff;
      position: absolute;
      left: 0;
      top: 50%;
      margin-top: -7px;
    }
  }
  .answer-wrap {
    .delete {
      margin-left: 10px;
    }
    .add-answer {
      padding-right: 10px;
      .or {
        color: #909399;
        margin-right: 4px;
      }
      .item {
        margin: 10px 0;
      }
    }
    .add-input-btn {
      font-size: 12px;
    }
  }

  .edit-options {
    margin-bottom: 20px;
    .input {
      flex: 1;
      margin: 0 15px;
      .el-input {
        margin-bottom: 10px;
      }
    }
    .title {
      font-size: 12px;
      font-weight: 400;
      color: #606266;
    }
    .content {
      flex: 1;
      margin: 0 10px;
      color: #909399;
    }
    .el-checkbox:last-of-type {
      margin-right: 30px;
    }
    .delete {
      color: #606266;
      font-size: 20px;
      cursor: pointer;
    }
  }
  .edit-learning {
    border: 1px solid #dcdfe6;
    color: #606266;
    font-weight: 500;
    font-size: 12px;
    border-radius: 3px;
    margin-right: 10px;
    .text,
    .close {
      padding: 0 8px;
      line-height: 26px;
      height: 26px;
    }
    .close {
      cursor: pointer;
      border-left: 1px solid #dcdfe6;
    }
  }
}
</style>
